package com.hs.sqlite3.utils;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class JsonRequestExample {
    public static String post(String u, String param) {
        try {
            // 创建URL对象
            URL url = new URL(u);
                    // 打开连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // 设置请求方法为POST
            connection.setRequestMethod("POST");
            // 设置请求的编码格式为UTF-8
            connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            // 启用输入输出流
            connection.setDoInput(true);
            connection.setDoOutput(true);
            // 创建请求数据
//            String jsonData =  "{\"name\":\"张三\",\"age\":20}";
            String jsonData =  param ;//"{\"name\":\"张三\",\"age\":20}";
            // 发送请求数据
            OutputStream outputStream = connection.getOutputStream();
            outputStream.write(jsonData.getBytes("UTF-8"));
            outputStream.flush();
            outputStream.close();

            // 读取响应数据
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            StringBuilder response = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();
            // 输出响应数据
            System.out.println(response.toString());
            return response.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }
}
